layui.use(['admin'], function () {
    let $ = layui.$
        , admin = layui.admin
        , setter = layui.setter
        , form = layui.form
        , laytpl = layui.laytpl;

    form.on('switch(statusSwitch)', function(data){
        let status = 0;
        if(data.elem.checked){
            status = 1;
        }
        form.val("layPopup", {
            "status": status
        });
    });

    let layerIndex = '';
    layui.data.sendParams = function (params) {
        layerIndex = params.lay_index;
    }

    let field = {};
    let xmSelect1 = '';
    let xmSelect2 = '';
    let xmSelect3 = '';
    // 获取数据
    admin.req({
        url: setter.request.domainName + '/admin/security.sensitiveData/add'
        , data: field
        , type: 'get'
        , loading: true // 是否开启加载框
        , done: function (res) {
            let tables = res.data.tables;
            let controllers = res.data.controllers;
            if(tables.toString() === '[object Object]'){
                let selectData = [];
                let initData = [];
                let data_table = form.val("layPopup").data_table;
                if(data_table){
                    initData = [data_table];
                    getTableFieldList(data_table);
                }
                for(let key in tables){
                    let temp = [];
                    temp['name'] = tables[key];
                    temp['value'] = key;
                    selectData.push(temp);
                }
                // 数据表下拉初始化
                xmSelect1 = initXmSelect("#xmSelectTable", selectData, initData, true, 1);
            }
            if(controllers.toString() === '[object Object]'){
                let selectData = [];
                let initData = [];
                let controller = form.val("layPopup").controller;
                if(controller){
                    initData = [controller];
                }
                for(let k in controllers){
                    let temp = [];
                    temp['name'] = controllers[k];
                    temp['value'] = k;
                    selectData.push(temp);
                }
                // 控制器下拉初始化
                xmSelect2 = initXmSelect("#xmSelectController", selectData, initData, true, 2);
            }
            // 敏感字段下拉初始化
            xmSelect3 = initXmSelect("#xmSelectField", [], [], false, 3);
        }
    })

    // 新增提交
    form.on('submit(laySubmitAdd)', function(data){
        let field = data.field; //获取提交的字段
        // 组装敏感字段提交数据
        let fieldsArr = [];
        if(xmSelect3){
            fieldsArr = xmSelect3.getValue();
        }
        let formData = form.val("layPopup");
        let fieldsData = [];
        let dataFields = [];
        layui.each(fieldsArr, function(index, item){
            let str = item.value
            let remarks = formData[str + '_remarks'];
            let obj = {
                'name': str,
                'value': remarks,
            };
            fieldsData.push(obj);
            dataFields.push(str);
        })
        field['fields'] = fieldsData;
        field['data_fields'] = dataFields;
        // 提交 Ajax 成功后，关闭当前弹层并重载表格
        admin.req({
            url: setter.request.domainName + '/admin/security.sensitiveData/add' //实际使用请改成服务端真实接口
            , data: field
            , type: 'POST'
            , loading: true // 是否开启加载框
            , done: function(res){
                layui.table.reload('seSDTable'); //重载表格
                admin.message({
                    title: '提交成功'
                    ,offset: '15px'
                    ,icon: 1
                    ,time: 1500
                })
                layer.close(layerIndex); //执行关闭
            }
        })
    });

    // 编辑提交
    form.on('submit(laySubmitEdit)', function(data){
        let field = data.field; //获取提交的字段
        // 组装敏感字段提交数据
        let fieldsArr = [];
        if(xmSelect3){
            fieldsArr = xmSelect3.getValue();
        }
        let formData = form.val("layPopup");
        let fieldsData = [];
        let dataFields = [];
        layui.each(fieldsArr, function(index, item){
            let str = item.value
            let remarks = formData[str + '_remarks'];
            let obj = {
                'name': str,
                'value': remarks,
            };
            fieldsData.push(obj);
            dataFields.push(str);
        })
        field['fields'] = fieldsData;
        field['data_fields'] = dataFields;
        // 提交 Ajax 成功后，关闭当前弹层并重载表格
        admin.req({
            url: setter.request.domainName + '/admin/security.sensitiveData/edit' //实际使用请改成服务端真实接口
            , data: field
            , type: 'POST'
            , loading: true // 是否开启加载框
            , done: function(res){
                layui.table.reload('seSDTable'); //重载表格
                admin.message({
                    title: '提交成功'
                    ,offset: '15px'
                    ,icon: 1
                    ,time: 1500
                })
                layer.close(layerIndex); //执行关闭
            }
        })
    });

    window.initXmSelect = function(ele, selectData = [], initData = [], is_radio = true, flag = 1){
        // 下拉选择框
        return xmSelect.render({
            el: ele,
            prop: {
                name: 'name',
                value: 'value',
            },
            language: 'zn',
            autoRow: true, // 自动换行
            filterable: true, // 开启搜索模式
            paging: true, // 开启分页
            pageSize: 50, // 每页显示条数
            initValue: initData, // 默认选中
            radio: is_radio, // 开启单选
            clickClose: is_radio, // 单选完关闭下拉
            toolbar: {
                show: true, // 显示工具条
                list: [ 'ALL', 'CLEAR', 'REVERSE' ], // 全选、清空、反选
            },
            data: selectData,
            on: function(data){
                //arr:  当前多选已选中的数据
                let arr = data.arr;
                //isAdd, 此次操作是新增还是删除
                let isAdd = data.isAdd;
                if(flag === 1){
                    // 表格下拉框
                    let tableName = '';
                    if(isAdd && arr.length > 0){
                        tableName = arr[0]['value'];
                        getTableFieldList(tableName);
                    }else{
                        getTableFieldList('');
                    }
                    form.val("layPopup", {
                        "data_table": tableName,
                        "field_str": '',
                    });
                }else if(flag === 2){
                    // 控制器下拉
                    let controller = '';
                    if(isAdd && arr.length > 0) {
                        controller = arr[0].value;
                        form.val("layPopup", {
                            "controller": controller,
                            "field_str": '',
                        });
                    }
                    form.val("layPopup", {
                        "controller": controller,
                        "field_str": '',
                    });
                }else if(flag === 3){
                    // 字段下拉
                    let getTpl = seSDLayTpl.innerHTML;
                    let html = laytpl(getTpl).render({
                        fieldList: arr
                    });
                    $('#seSDLayView').html(html);
                }
            }
        })
    }

    window.getTableFieldList = function(tableName){
        if(!tableName){
            // 敏感字段下拉赋值
            xmSelect3.update({
                data: [],
                initValue: [],
            })

            let getTpl = seSDLayTpl.innerHTML;
            let html = laytpl(getTpl).render({
                fieldList: []
            });
            $('#seSDLayView').html(html);
            return false;
        }
        // 获取数据
        admin.req({
            url: setter.request.domainName + '/admin/ajax/getTableFieldList'
            , data: {'table': tableName, 'clean': 1}
            , type: 'get'
            , loading: true // 是否开启加载框
            , done: function (res) {
                let fieldList = res.data.fieldlist;
                if(fieldList.toString() === '[object Object]'){
                    let selectData = [];
                    let initData = [];
                    let fieldStr = form.val("layPopup").field_str;
                    if(fieldStr){
                        let fieldArr = fieldStr.split(",");
                        if(Array.isArray(fieldArr) === true){
                            initData = fieldArr;
                        }
                    }
                    for(let k in fieldList){
                        let temp = [];
                        let remarks = fieldList[k];
                        temp['name'] =  k + ' - ' + remarks;
                        temp['value'] = k;
                        temp['remarks'] = remarks;
                        selectData.push(temp);
                    }

                    // 敏感字段下拉赋值
                    xmSelect3.update({
                        data: selectData,
                        initValue: initData,
                    })

                    let getTpl = seSDLayTpl.innerHTML;
                    let html = laytpl(getTpl).render({
                        fieldList: xmSelect3.getValue()
                    });
                    $('#seSDLayView').html(html);

                }
                form.val("layPopup", {
                    "primary_key": res.data.pk
                });
            }
        })
    }

})
